﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class ZoneFileCell
{
    public string zonefilename;

    public string zonefilecontent;

    public string zoneRelationfinename;

    public string zoneRelationfinecontent;
}

public class ZoneFile
{
    public ZoneFile()
    {
        LoadZoneFiles();
    }

    List<ZoneFileCell> zonefiles = new List<ZoneFileCell>();

    string _Dir = ZoneFileOnAndroid.ZoneFileFolder + "/zonedata/";

    void LoadZoneFiles()
    {
        string[] _files = System.IO.Directory.GetFiles(_Dir, "*_zone.txt");
        string[] _relationfiles = System.IO.Directory.GetFiles(_Dir, "*_relation.txt");

        for(int i = 0; i < _files.Length; ++i)
        {
            ZoneFileCell cell = new ZoneFileCell();
            cell.zonefilename = Path.GetFileNameWithoutExtension(_files[i]);
            cell.zonefilecontent = ReadFile(cell.zonefilename);
            cell.zoneRelationfinename = cell.zonefilename.Replace("_zone", "_relation");
            cell.zoneRelationfinecontent = ReadFile(cell.zoneRelationfinename);

            zonefiles.Add(cell);
        }

    }

    void LoadZoneFilesApk()
    {

    }

    public ZoneFileCell GetZonecell(int index)
    {
        return zonefiles[index];
    }

    public string GetZoneData(int index)
    {
        ZoneFileCell cell = zonefiles[index];

        return cell.zonefilecontent;
    }

    public void SaveZoneData(int index, string content)
    {
        ZoneFileCell cell = zonefiles[index];
        cell.zonefilecontent = content;

        SaveFile(cell.zonefilename, content);
    }

    public string GetZoneRelationData(int index)
    {
        ZoneFileCell cell = zonefiles[index];

        return cell.zoneRelationfinecontent;
    }

    public void SaveZoneRelationData(int index, string content)
    {
        ZoneFileCell cell = zonefiles[index];
        cell.zoneRelationfinecontent = content;

        SaveFile(cell.zoneRelationfinename, content);
    }

    public int GetZoneCount()
    {
        return zonefiles.Count;
    }

    string ReadFile(string file)
    {
        string path = _Dir + file + ".txt";

        if (!File.Exists(path))
            return string.Empty;

        string content = File.ReadAllText(path);

        return content;

    }

    void SaveFile(string file, string content)
    {
        string path = _Dir + file + ".txt";

        var streamWriter = new StreamWriter(path);
        streamWriter.Write(content);
        streamWriter.Close();
    }
}
